import cv2

imgage = cv2.imread("../images/flower.png")
h,w,_ = imgage.shape
img_gray = cv2.cvtColor(imgage,cv2.COLOR_BGR2GRAY)
ret,img_binary = cv2.threshold(img_gray,127,255,cv2.THRESH_BINARY)
print(ret)

""" 
自己写算法实现
# 1. 创建和原图同等大小的图像
img_binary = np.zeros_like(img_gray)
# 2. 指定阈值和maxval
thresh = 127
maxval = 255
# 3. 循环遍历每一个灰度图的像素点与阈值进行比较
        # 方法1：二值化阈值处理。像素灰度值大于阈值时设为 maxval，小于等于阈值时设为 0
        # 方法2：反二值化阈值处理。像素灰度值大于阈值时设为 0，小于等于阈值时设为 maxval。
        if img_gray[i, j] > thresh:
            img_binary[i, j] = 0
        else:
            img_binary[i, j] = maxval
"""
cv2.imshow('original image', imgage)
cv2.imshow('gray image', img_gray)
cv2.imshow('binary image', img_binary)
cv2.waitKey(0)